<template>
  <div class="admin-user-page">
    <!-- 搜索卡片 -->
    <div class="search-card">
      <a-form
        layout="inline"
        :model="formSerchParams"
        @submit="doSerach"
        class="search-form"
      >
        <a-form-item field="resultName" label="结果名称" class="form-item">
          <a-input
            allow-clear
            v-model="formSerchParams.resultName"
            placeholder="请输入结果名称"
            class="search-input"
          />
        </a-form-item>

        <a-form-item field="resultDesc" label="结果描述" class="form-item">
          <a-input
            allow-clear
            v-model="formSerchParams.resultDesc"
            placeholder="请输入结果描述"
            class="search-input"
          />
        </a-form-item>

        <a-form-item field="appId" label="应用ID" class="form-item">
          <a-input
            allow-clear
            v-model="formSerchParams.appId"
            placeholder="请输入应用ID"
            class="search-input"
          />
        </a-form-item>

        <a-form-item field="userId" label="用户ID" class="form-item">
          <a-input
            allow-clear
            v-model="formSerchParams.userId"
            placeholder="请输入用户ID"
            class="search-input"
          />
        </a-form-item>

        <a-form-item>
          <a-button type="primary" html-type="submit" class="search-btn">
            <template #icon>
              <icon-search />
            </template>
            搜索
          </a-button>
        </a-form-item>
      </a-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-card">
      <a-table
        :columns="columns"
        :data="dataList"
        :pagination="pagination"
        :row-class="setRowClass"
        @page-change="onPageChange"
        row-key="id"
      >
        <!-- 结果图片 -->
        <template #resultPicture="{ record }">
          <a-image
            width="64"
            :src="record.resultPicture"
            :preview="!!record.resultPicture"
          />
        </template>

        <!-- 应用类型 -->
        <template #appType="{ record }">
          <a-tag color="arcoblue" size="small">
            {{ APP_TYPE_MAP[record.appType] }}
          </a-tag>
        </template>

        <!-- 评分策略 -->
        <template #scoringStrategy="{ record }">
          <a-tag color="purple" size="small">
            {{ APP_SCORING_STRATEGY_MAP[record.scoringStrategy] }}
          </a-tag>
        </template>

        <!-- 用户答案（简化显示） -->
        <template #choices="{ record }">
          <a-tooltip
            :content="JSON.stringify(record.choices)"
            position="top"
            mini
          >
            <div class="choices-content">
              {{ truncateChoices(record.choices) }}
            </div>
          </a-tooltip>
        </template>

        <!-- 时间格式化 -->
        <template #createTime="{ record }">
          {{ dayjs(record.createTime).format("YYYY-MM-DD") }}
        </template>

        <!-- 操作列 -->
        <template #optional="{ record }">
          <a-popconfirm
            content="确认要删除该记录吗？"
            type="error"
            @ok="doDelete(record)"
          >
            <a-button status="danger" size="small">删除</a-button>
          </a-popconfirm>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watchEffect } from "vue";
import { API } from "@/api/typings";
import message from "@arco-design/web-vue/es/message";
import { dayjs } from "@arco-design/web-vue/es/_utils/date";
import {
  deleteUserAnswerUsingPost,
  listUserAnswerByPageUsingPost,
} from "@/api/userAnswerController";
import { APP_SCORING_STRATEGY_MAP, APP_TYPE_MAP } from "@/constant/app";

// 初始化搜索条件
const initSearchParams = {
  current: 1,
  pageSize: 10,
};

// 分页配置
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: true,
  showJumper: true,
  showPageSize: true,
  pageSizeOptions: [10, 20, 50],
});

// 执行搜索
const doSerach = () => {
  serachParame.value = {
    ...initSearchParams,
    ...formSerchParams.value,
  };
};

const formSerchParams = ref<API.UserAnswerQueryRequest>({});

const serachParame = ref<API.UserAnswerQueryRequest>({
  ...initSearchParams,
});

const dataList = ref<API.UserAnswer[]>([]);

const total = ref<number>(0);

/**
 * 加载数据
 */
const loadData = async () => {
  const res = await listUserAnswerByPageUsingPost(serachParame.value);
  if (res.data.code === 0) {
    dataList.value = res.data.data?.records || [];
    total.value = res.data.data?.total || 0;
    pagination.total = total.value;
  } else {
    message.error("获取数据失败", res.data.message);
  }
};

/**
 * 分页变化时重新加载数据
 * @param page 当前页码
 */
const onPageChange = (page: number) => {
  serachParame.value = {
    ...serachParame.value,
    current: page,
  };
};

/**
 * 删除记录
 * @param record 用户答案记录
 */
const doDelete = async (record: API.UserAnswer) => {
  if (!record.id) {
    return;
  }

  const res = await deleteUserAnswerUsingPost({
    id: record.id,
  });
  if (res.data.code === 0) {
    message.success("删除成功");
    loadData();
  } else {
    message.error("删除用户回答失败", res.data.message);
  }
};

// 设置表格行样式（斑马纹）
const setRowClass = (record: API.UserAnswer, index: number) => {
  return index % 2 === 1 ? "stripe-row" : "";
};

// 截短用户答案显示
const truncateChoices = (choices: any) => {
  if (!choices) return "-";
  const str = JSON.stringify(choices);
  return str.length > 15 ? str.substring(0, 15) + "..." : str;
};

// 监听搜索参数变化自动加载数据
watchEffect(() => {
  loadData();
});

// 表格列配置
const columns = [
  {
    title: "ID",
    dataIndex: "id",
    width: 80,
    ellipsis: true,
    tooltip: true,
  },
  {
    title: "应用ID",
    dataIndex: "appId",
    width: 100,
    ellipsis: true,
  },
  {
    title: "应用类型",
    dataIndex: "appType",
    slotName: "appType",
    width: 100,
    align: "center",
  },
  {
    title: "评分策略",
    dataIndex: "scoringStrategy",
    slotName: "scoringStrategy",
    width: 120,
    align: "center",
  },
  {
    title: "用户答案",
    dataIndex: "choices",
    slotName: "choices",
    width: 120,
  },
  {
    title: "结果名称",
    dataIndex: "resultName",
    width: 150,
    ellipsis: true,
    tooltip: true,
  },
  {
    title: "结果描述",
    dataIndex: "resultDesc",
    width: 180,
    ellipsis: true,
    tooltip: true,
  },
  {
    title: "结果图片",
    dataIndex: "resultPicture",
    slotName: "resultPicture",
    width: 100,
    align: "center",
  },
  {
    title: "得分",
    dataIndex: "resultScore",
    width: 80,
    align: "center",
  },
  {
    title: "用户ID",
    dataIndex: "userId",
    width: 100,
    ellipsis: true,
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    slotName: "createTime",
    width: 140,
  },
  {
    title: "操作",
    slotName: "optional",
    width: 80,
    align: "center",
  },
];
</script>

<style scoped>
.admin-user-page {
  padding: 16px;
  height: 100%;
  box-sizing: border-box;
}

.search-card {
  margin-bottom: 16px;
  padding: 16px;
  background-color: var(--color-bg-2);
  border-radius: 4px;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.03);
}

.search-form {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
  align-items: center;
}

.form-item {
  margin-right: 0;
  margin-bottom: 0;
}

.form-item .arco-form-item-label {
  font-weight: 500;
}

.search-input {
  width: 180px;
}

.search-btn {
  border-radius: 4px;
}

.table-card {
  background-color: var(--color-bg-2);
  border-radius: 4px;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.03);
}

.table-card .arco-table-tr {
  transition: background-color 0.2s;
}

.table-card .arco-table-tr:hover {
  background-color: var(--color-fill-1) !important;
}

.table-card .stripe-row {
  background-color: var(--color-fill-1);
}

.table-card .arco-table-th {
  background-color: var(--color-fill-1);
  font-weight: 500;
}

.choices-content {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
}

@media (max-width: 768px) {
  .search-input {
    width: 160px;
  }

  .table-card {
    overflow-x: auto;
  }
}
</style>
